<template>
  <section class="p-4 cursor-pointer">
    <header class="flex items-center justify-between pl-14 pr-[440px] py-3">
      <span> 文章名 </span>
      <div class="flex items-center gap-40">
        <span> 最近修改 </span>
        <span>大小</span>
      </div>
    </header>
    <div class="divider mx-6"></div>
    <article
      v-for="article in recycleBinArticles"
      :key="article.id"
      class="flex items-center justify-between pl-12 pr-72 py-3 rounded hover:bg-[#f1f1f1] group"
    >
      <span> {{ article.title }} </span>
      <div class="flex items-center gap-28 text-[#999]">
        <span> {{ formatTime(article.delete_time!) }} </span>
        <span> {{ estimateStringMemorySizeInKB(article.content) }} KB </span>
        <cl-icon
          icon="More"
          color="#000"
          class="opacity-0 group-hover:opacity-100 transition-opacity duration-200"
          @click="handleShowMenu($event, article)"
        />
      </div>
    </article>
    <cl-menu trigger="manual" ref="menuRef">
      <div class="menu-item text-[#606266]" @click="handleRestore">恢复</div>
      <div class="menu-item text-red-500" @click="handleDelete">彻底删除</div>
    </cl-menu>
  </section>
</template>

<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useArticleStore } from "@/stores/article";
import { ElMessageBox } from "element-plus";
import ClMenu from "@/components/cl-menu/index.vue";
const articleStore = useArticleStore();
const { recycleBinArticles } = storeToRefs(articleStore);

let currentArticle: ArticleWithId | null = null;

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleString();
};

function estimateStringMemorySizeInKB(str: string) {
  const sizeInBytes = str.length * 2;
  return (sizeInBytes / 1024).toFixed(2);
}

const menuRef = ref<InstanceType<typeof ClMenu>>();

const handleShowMenu = (e: MouseEvent, article: ArticleWithId) => {
  currentArticle = article;
  menuRef.value?.open({ x: e.clientX, y: e.clientY });
};

const handleRestore = async () => {
  await articleStore.restoreFromRecycle(currentArticle?.id!);
};

const handleDelete = async () => {
  await articleStore.deleteArticlePermanently(currentArticle?.id!);
};

// const handleEmpty = async () => {
//   await ElMessageBox.confirm("确定要清空回收站吗？此操作不可逆！", "警告", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//   });
//   await articleStore.emptyRecycleBin();
// };

// 初始化加载
onMounted(() => {
  articleStore.loadDeletedArticles();
});
</script>

<style lang="scss" scoped>
.menu-item {
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

.divider {
  height: 1px;
  background-color: var(--el-border-color-light);
  @apply my-2;
}

.article-item {
  @apply transition-colors duration-200;
}

.cl-icon[icon="More"] {
  @apply opacity-0;
}

.group:hover .cl-icon[icon="More"] {
  @apply opacity-100;
}
</style>
